'''
# -*- coding:utf-8 -*-
# @Project: DevOps_api
# @Date: 2023/3/12 - 22:06
# @Author: ysg
# @Describe: 

Ops_mixins.py
'''
from rest_framework.mixins import ListModelMixin, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, \
    DestroyModelMixin
from utils.Ops_responses import OpsResponse
from utils.log_db import handle_log


class OpsListModelMixin(ListModelMixin):
    def list(self, request, *args, **kwargs):
        ret = super().list(self, request, *args, **kwargs)
        return OpsResponse(data=ret.data)


class OpsUpdateModelMixin(UpdateModelMixin):
    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        if not serializer.is_valid():
            return OpsResponse()
        res = self.perform_update(serializer)
        handle_log(str(request.path), f"修改 {instance if instance else '00000'}")
        return res or OpsResponse(data=serializer.data)


class OpsDestroyModelMixin(DestroyModelMixin):
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        handle_log(str(request.path), f'删除记录 {instance}')
        instance.delete()
        return OpsResponse()


class OpsCreateModelMixin(CreateModelMixin):
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        handle_log(str(request.path), f'新增记录')
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return OpsResponse(data=serializer.data, headers=headers)

    def perform_create(self, serializer):
        serializer.save()